/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.bef.core.action.tcc;

import com.inspur.edp.bef.api.be.IBENodeEntityContext;
import com.inspur.edp.bef.core.tcc.builtinimpls.BefTccHandlerAssembler;
import com.inspur.edp.bef.spi.action.tcc.BefTccHandler;
import com.inspur.edp.bef.api.action.tcc.TccHandlerContext;
import com.inspur.edp.caf.transaction.api.annoation.tcc.BusinessActionContext;
import com.inspur.edp.cef.entity.accessor.base.AccessorComparer;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import io.iec.edp.caf.boot.context.CAFContext;
import java.util.List;

public class EntityCustomTccExecutor {

  private final boolean success;
  private final BefTccHandlerAssembler assembler;
  private final IBENodeEntityContext beContext;
  private final BusinessActionContext tccContext;
  private final IChangeDetail reverseChg;

  public EntityCustomTccExecutor(IBENodeEntityContext beCtx, IChangeDetail reverseChg, BefTccHandlerAssembler assembler,
      BusinessActionContext tccContext, boolean success) {
    this.assembler = assembler;
    this.reverseChg = reverseChg;
    this.success = success;
    this.tccContext = tccContext;
    this.beContext = beCtx;
  }

  public void execute() {
    List<BefTccHandler> handlers = assembler.getHandlers();
    String currBizCtxId = CAFContext.current.getBizContext().getId();
    TccHandlerContext handlerCtx = new TccHandlerContextImpl(tccContext, beContext, reverseChg);
    if (handlers != null && !handlers.isEmpty()) {
      for (BefTccHandler handler : handlers) {
        executeHandler(handler, currBizCtxId, handlerCtx);
      }
    }

    List<BefTccHandler> childHandlers = assembler.getChildAssemblers();
    if (childHandlers != null && !childHandlers.isEmpty()) {
      for (BefTccHandler handler : childHandlers) {
        executeHandler(handler, currBizCtxId, handlerCtx);
      }
    }
  }

  private void executeHandler(BefTccHandler handler, String currBizCtxId,
      TccHandlerContext handlerCtx) {
    if (!handler.canExecute(handlerCtx)) {
      return;
    }

    if (success) {
      handler.confirm(handlerCtx);
    } else {
      handler.cancel(handlerCtx);
    }
    if (!AccessorComparer.equals(currBizCtxId, CAFContext.current.getBizContext().getId())) {
      throw new RuntimeException("BizContext发生变化在" + handler.getClass().getTypeName());
    }
  }
}
